#coding=utf-8
import sys

from uliweb.orm import get_model, set_dispatch_send, Begin, Commit, Rollback

set_dispatch_send(False)

log = open('log.txt', 'w')

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import get_apps, get_app_dir, Dispatcher

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    try:
        Begin()
        try:
            process(args, options, global_options)
            Commit()
        except:
            Rollback()
            import traceback
            traceback.print_exc()
    finally:
        log.close()
        
def process(args, options, global_options):
    from sqlalchemy.sql import func
    from uliweb import settings
    
    P = get_model('plan')
    PE = get_model('planexecute')
    PE.modified_user.default = None
    
    n = 0
    for plan in P.all():
        
        #增加主任务计划，要判断systems中是否有当前system
        if plan.systems.has(plan.task._task_sys_):
            e = PE.get((PE.c.task==plan._task_) & (PE.c.plan==plan.id) & (PE.c.system==plan.task._task_sys_))
            if not e:
                e = PE(task=plan._task_, plan=plan.id, system=plan.task._task_sys_, type=plan.type)
                e.save()
                n += 1
        
        #保存子任务
        for t in plan.task.child_tasks.all():
            if plan.systems.has(t.task_sys):
                e = PE.get((PE.c.task==t.id) & (PE.c.plan==plan.id) & (PE.c.system==t._task_sys_))
                if not e:
                    e = PE(task=t.id, plan=plan.id, type=plan.type, system=t._task_sys_)
                    e.save()
                    n += 1
                    
    print 'Total: %d' % n
    
